﻿#ifndef _CELL_CONFIG_HPP_
#define _CELL_CONFIG_HPP_

#include <string>
#include <string.h>
#include <map>

class CELLConfig
{
public:
	static CELLConfig& Instance()
	{
		static CELLConfig obj;
		return obj;
	}

	void Init(int argc, char* argv[])
	{
		_exePath = argv[0];
		for (int i = 1; i < argc; ++i)
		{
			madeCmd(argv[i]);
		}
	}

	void madeCmd(char* cmd)
	{
		char* val = strchr(cmd, '=');
		if (val)
		{
			// =127.0.0.1
			*val = '\0';
			// \0127.0.0.1
			++val;
			_kv[cmd] = val; // cmd此时等号已被换成终止符
			CELLLog_Info("madeCmd<%s = %s>", cmd, val);
		}
		else
		{
			_kv[cmd] = "";
			// CELLLog_Warning("madeCmd get a key, but has no value!");
		}
	}

	const char* getStr(const char* argName, const char* def)
	{
		static char tmp[512] = { 0 };
		auto iter = _kv.find(argName);
		if (iter == _kv.end())
		{
			sprintf(tmp, "%s", def);
			CELLLog_Warning("CELLConfig getStr return a default value %s", def);
		}
		else
		{
			sprintf(tmp, "%s", iter->second.c_str());
			CELLLog_Info("CELLConfig getStr argName = %s, return value = %s", argName, tmp);
		}
		return tmp;
	}

	int getNum(const char* argName, int def)
	{
		auto iter = _kv.find(argName);
		if (iter != _kv.end())
		{
			def = atoi(iter->second.c_str());
			CELLLog_Info("CELLConfig getNum argName = %s, return value = %d", argName, def);
		}
		else
		{
			CELLLog_Warning("CELLConfig getInt return a default value %d", def);
		}
		return def;
	}

	bool HasKey(const char* name)
	{
		bool ret = _kv.find(name) != _kv.end();
		CELLLog_Info("CELLConfig HasKey %s, return %d", name, (int)ret);
		return ret;
	}
private:
	CELLConfig()
	{

	}
	// 当前可执行文件的路径
	std::string _exePath;
	// 键值对
	std::map<std::string, std::string> _kv;
};

#endif // #ifndef _CELL_CONFIG_HPP_
